package com.example.geohash.service;

import io.lettuce.core.RedisCommandExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * liuyu07
 */
@Service
public class RedisGeohashServiceImpl implements RedisGeohashService {

    @Autowired
    RedisTemplate redisTemplate;
    public static final String REDIS_GEO_KEY = "station";
    private static final Logger logger = LoggerFactory.getLogger(RedisGeohashServiceImpl.class);

    @Override
    public void insertStation(String stationCode, double lng, double lat) {
        logger.info("参数："+stationCode+", "+lng+", "+lat);
        try {
            //有效的经度从-180度到180度。
            //有效的纬度从-85.05112878度到85.05112878度。
            if(lng <-180 || lng > 180){
                return;
            }
            if(lat<-85 || lat > 85){
                return;
            }
            Point point = new Point(lng,lat);
            redisTemplate.opsForGeo().add(REDIS_GEO_KEY, point, stationCode);
        }catch (RedisCommandExecutionException e){
            logger.error("出错了");
        }
    }

    @Override
    public List getNearlyStation(float lng, float lat, int radius) {
        Point center = new Point(lng, lat);
        Distance distance = new Distance(radius, Metrics.KILOMETERS);
        Circle within = new Circle(center, distance);
        // order by 距离 limit 10, 同时返回距离中心点的距离
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().limit(10).sortAscending();
        GeoResults list = redisTemplate.opsForGeo().radius(REDIS_GEO_KEY, within, args);
        return list.getContent();
    }

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }
}
